package com.toubutu.audio.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.toubutu.audio.admin.dto.CategoryDto;
import com.toubutu.audio.admin.vo.VideoCategoryTreeVo;
import com.toubutu.audio.entity.VideoCategory;
import com.toubutu.audio.mapper.VideoCategoryMapper;
import com.toubutu.audio.service.VideoCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.toubutu.common.BusinessException;
import com.toubutu.common.StatusCodeEnum;
import com.toubutu.constants.BaseConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 戒躁
 * @since 2024-01-10
 */
@Service
public class VideoCategoryServiceImpl extends ServiceImpl<VideoCategoryMapper, VideoCategory> implements VideoCategoryService {

    @Override
    public List<VideoCategoryTreeVo> getVideoCategoryTree() {
        LambdaQueryWrapper<VideoCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VideoCategory::getIsDelete, BaseConstants.UN_DELETED);
        List<VideoCategory> allCategory = list(wrapper);
        if (allCategory.isEmpty()) return Collections.emptyList();
        return allCategory.stream().filter(c -> c.getParentId().equals(BaseConstants.PARENT_MENU_ID))
                .map(p->{
                    VideoCategoryTreeVo videoCategoryTreeVo = po2Vo(p);
                    List<VideoCategoryTreeVo> childrenList = getChildrenList(p.getCategoryId(), allCategory);
                    videoCategoryTreeVo.setChildren(childrenList);
                    return videoCategoryTreeVo;
                }).collect(Collectors.toList());
    }

    @Override
    public List<VideoCategory> getAllParentCategoryList() {
        LambdaQueryWrapper<VideoCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VideoCategory::getIsDelete,BaseConstants.UN_DELETED)
                .eq(VideoCategory::getParentId,BaseConstants.PARENT_MENU_ID);
        return list(queryWrapper);
    }

    @Override
    public List<VideoCategory> getChildrenCategoryList(Integer parentId) {
        LambdaQueryWrapper<VideoCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VideoCategory::getParentId,parentId).eq(VideoCategory::getIsDelete,BaseConstants.UN_DELETED);
        return list(queryWrapper);
    }

    @Override
    public void batchDeleteCategory(List<Integer> ids) {
        List<Integer> parentIds = new ArrayList<>();
        getChildrenIsParentIds(ids, parentIds);
        LambdaUpdateWrapper<VideoCategory> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(VideoCategory::getCategoryId,ids);
        if (!parentIds.isEmpty()){
             wrapper.in(VideoCategory::getParentId,parentIds);
        }
        wrapper.set(VideoCategory::getIsDelete,BaseConstants.DELETED);
        update(wrapper);
    }

    @Override
    public VideoCategory getVideoCategoryInfo(Integer categoryId) {
        LambdaQueryWrapper<VideoCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VideoCategory::getCategoryId,categoryId).eq(VideoCategory::getIsDelete,BaseConstants.UN_DELETED);
        VideoCategory videoCategory = getOne(queryWrapper);
        if (videoCategory==null){
            throw new BusinessException(StatusCodeEnum.NOT_FOUND);
        }
        return videoCategory;
    }

    /**
     * 获取要删除的分类下的所有父级id
     * @return List
     */
    private void getChildrenIsParentIds(List<Integer> ids,List<Integer> result){
        LambdaQueryWrapper<VideoCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(VideoCategory::getParentId,ids);
        List<VideoCategory> list = list(wrapper);
        if (list.isEmpty()){
            return  ;
        }
        List<Integer> collect = list.stream().map(v -> {
            result.add(v.getCategoryId());
            return v.getCategoryId();
        }).collect(Collectors.toList());
        getChildrenIsParentIds(collect,result);
    }
    @Override
    public void addCategory(CategoryDto categoryDto) {
        //先查询分类名称在同层级下是否已存在
        checkNameIsExist(categoryDto);
        VideoCategory videoCategory = categoryDto.toPo();
        save(videoCategory);
    }

    @Override
    public void updateCategoryById(CategoryDto categoryDto) {
        checkNameIsExist(categoryDto);
        LambdaUpdateWrapper<VideoCategory> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(VideoCategory::getCategoryId,categoryDto.getCategoryId())
                .set(VideoCategory::getCategoryName,categoryDto.getCategoryName());
        update(updateWrapper);
    }

    @Override
    public Map<Integer, VideoCategory> getCategoryMapInfo(List<Integer> categoryIds) {
        LambdaQueryWrapper<VideoCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VideoCategory::getIsDelete,BaseConstants.UN_DELETED)
                .in(VideoCategory::getCategoryId,categoryIds);
        List<VideoCategory> categoryList = list(queryWrapper);
        if (categoryList.isEmpty()){
            return new HashMap<>();
        }
        List<Integer> parentIds = categoryList.stream().map(VideoCategory::getParentId)
                .filter(parentId -> parentId != BaseConstants.PARENT_MENU_ID).collect(Collectors.toList());
        if (parentIds.isEmpty()){
            return categoryList.stream().collect(Collectors.toMap(VideoCategory::getCategoryId,v->v));
        }
        queryWrapper.clear();
        queryWrapper.eq(VideoCategory::getIsDelete,BaseConstants.UN_DELETED)
                .in(VideoCategory::getCategoryId,parentIds);
        List<VideoCategory> parentCategoryList = list(queryWrapper);
        if (parentCategoryList.isEmpty()){
            return categoryList.stream().collect(Collectors.toMap(VideoCategory::getCategoryId,v->v));
        }
        categoryList.addAll(parentCategoryList);
        return categoryList.stream().collect(Collectors.toMap(VideoCategory::getCategoryId,v->v,(v1,v2)->v1));
    }


    private void checkNameIsExist(CategoryDto categoryDto){
        LambdaQueryWrapper<VideoCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VideoCategory::getParentId,categoryDto.getParentId());
        wrapper.eq(VideoCategory::getCategoryName,categoryDto.getCategoryName());
        wrapper.eq(VideoCategory::getIsDelete,BaseConstants.UN_DELETED);
        VideoCategory category = getOne(wrapper);
        if (category!=null)throw new BusinessException(StatusCodeEnum.USER_HANDLE.getCode(),"分类名在同层级下已存在!");
    }

    private VideoCategoryTreeVo po2Vo(VideoCategory category) {
        VideoCategoryTreeVo videoCategoryTreeVo = new VideoCategoryTreeVo();
        BeanUtils.copyProperties(category, videoCategoryTreeVo);
        return videoCategoryTreeVo;
    }

    private List<VideoCategoryTreeVo> getChildrenList(Integer parentId,List<VideoCategory> source){
       return source.stream().filter(c->c.getParentId().equals(parentId))
                .map(c->{
                    VideoCategoryTreeVo videoCategoryTreeVo = po2Vo(c);
                    List<VideoCategoryTreeVo> childrenList = getChildrenList(c.getCategoryId(), source);
                    videoCategoryTreeVo.setChildren(childrenList);
                    return videoCategoryTreeVo;
                }).collect(Collectors.toList());
    }
}
